package servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dbOperator.AdvancedOperation;
import dbOperator.BasicOperation;

/**
 * Servlet implementation class ISBN
 */
@WebServlet("/ISBN")
//https://route.showapi.com/1626-1?isbn=9787208061644&showapi_appid=105792&showapi_sign=23960e7799d54ed2bad13cc16b8fca91

public class ISBN extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    /**这个函数用于获取res中的id
	 * @param res
	 * @param id
	 * @return 返回从res中读取的id
     * makisemirai注释
	 */
	private static String getInfo(String res,String id) {
    	int i = res.indexOf("\""+id+"\"");
    	//System.out.println(i);
    	if (i==-1) return null;
		String info = res.substring(i + id.length()+3);
		if(info.indexOf('\"') == 0) {
			info = info.substring(1);
			i = info.indexOf('\"');
		}
		else {
			int t1 = info.indexOf(',');
			int t2 = info.indexOf('}');
			if(t1>=0&&t2>=0) i=t1<t2?t1:t2;
			else if(t1==-1) i=t2;
			else i=t1;
		}
		return info.substring(0, i);
    }
	/**这个函数用于提取输入的ISBN来构建URL对象，打印从数据流中读取、转换而成的数据，并向数据库中插入该书籍信息
	 * @param request 客户端的请求
	 * @param response 给客户端的响应
	 * @throws ServletException
	 * @throws IOException
     * makisemirai注释
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Cookie cookies[] = request.getCookies();
		if (cookies == null) {
			response.sendRedirect("index.html");
			return;
		}
		for (Cookie c : cookies) {
			if (c.getName().equals("LoginInfo")) {
				String currentCookie = c.getValue();
				Connection con = BasicOperation.getConnection();
				int uid;
				try {
					uid = AdvancedOperation.getUidbyCookie(con, currentCookie);
					if (AdvancedOperation.getIdentity(con, uid) != 2)
						return;
				} catch (SQLException e) {
					e.printStackTrace();
				}
				String ISBN = request.getParameter("apiISBN");
				ISBN = ISBN.replace("-", "");
				URL url = new URL("https://route.showapi.com/1626-1?isbn=" + ISBN
						+ "&showapi_appid=105792&showapi_sign=23960e7799d54ed2bad13cc16b8fca91");
				URLConnection connection = url.openConnection();
				connection.setRequestProperty("User-Agent",
						"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.884.400 QQBrowser/9.0.2524.400");
				InputStream in = connection.getInputStream();
				InputStreamReader isr = new InputStreamReader(in, "utf-8");
				BufferedReader br = new BufferedReader(isr);
				String line;
				StringBuilder sb = new StringBuilder();
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
				line = sb.toString();
				System.out.println(line);
				 br.close();
		            isr.close();
		            in.close();
				if(!getInfo(line,"remark").equals("success")) {response.getWriter().println("<script>alert('FAILED to get the information through given ISBN!');window.location.href='" + request.getHeader("Referer") + "'</script>");return;}
		        String publisher = getInfo(line, "publisher");
				String author = getInfo(line,"author");
				String name = getInfo(line,"title");
				String price = getInfo(line,"price");
				StringBuffer sbf=new StringBuffer(ISBN);
				sbf.insert(3, '-');sbf.insert(5, '-');sbf.insert(10, '-');sbf.insert(15, '-');
				ISBN=sbf.toString();
				Statement sql;
				try {
					sql = con.createStatement();
					sql.executeUpdate("insert into Book(name,category,author,publisher,ISBN,price) values('" + name + "','','" + author + "','" + publisher + "','" + ISBN + "','" + price + "')");
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		response.sendRedirect(request.getHeader("Referer"));
	}
}
